<?php

namespace app\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 *
 */
class ForwardRule extends BaseModel
{

    /**
     * @param string $keyword
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getForwardRules(string $keyword = ''): array
    {
        $where = [];
        $where[] = ['status', '=', 1];
        if (!empty($keyword)) {
            $where[] = ['keyword', 'eq', trim($keyword)];
        }
        return $this->where($where)
            ->field('id,keyword,forward_wxid')
            ->select()->toArray() ?? [];
    }

    /**
     * 新增或者更新转发规则
     * @param array $rule_data
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createOrUpdateForwardRule(array $rule_data): void
    {
        $where = [
            'keyword' => $rule_data['keyword'],
            'forward_wxid' => $rule_data['forward_wxid'],
        ];
        $find = $this->where($where)->find();
        if (empty($find)) {
            $this->save($rule_data);
        } else {
            $this->where($where)->update($rule_data);
        }
    }
}
